package com.kaka.bus.engine.borrow.person;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.adapter.SelfPageAdapter;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.City;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.engine.borrow.person.step.Step1Fragment;
import com.kaka.bus.engine.borrow.person.step.Step2Fragment;
import com.kaka.bus.engine.borrow.person.step.Step3Fragment;
import com.kaka.bus.engine.home.main.limit.LimitActivity;
import com.kaka.bus.engine.other.DrainageActivity;
import com.kaka.bus.util.U;
import com.kaka.bus.util.UserUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by zhangqi on 2017/12/21.
 * e-mail : ${email}
 * desc :
 */

public class PersonActivity extends BaseActivity<PersonPresenter> implements PersonContract.View {


    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.person_self)
    RadioButton mPersonSelf;
    @BindView(R.id.bg_person_job)
    RadioButton mBgPersonJob;
    @BindView(R.id.bg_person_shehui)
    RadioButton mBgPersonShehui;
    @BindView(R.id.rg_person)
    RadioGroup mRgPerson;
    @BindView(R.id.vp_person)
    ViewPager mVpPerson;

    private Map<String, ArrayList<String>> mCityMap;
    private List<Fragment> mPageList;
    private Step1Fragment mStep1Fragment;
    private Step2Fragment mStep2Fragment;
    private Step3Fragment mStep3Fragment;
    private int mCode;
    private RxPermissions mRxPermissions;
    public LinkedHashMap<String, String> mPMap;

    @Override
    protected void initView() {
        super.initView();
        mToolbarName.setText("个人信息");
        mToolbarBack.setOnClickListener(v -> finish());

        mRxPermissions = new RxPermissions(this);
        /**
         * 默认选择di第一个
         */
        mRgPerson.check(R.id.person_self);

        /**
         * 加载缓存中
         */
        mPMap = UserUtil.getCache(UserUtil.PERSONINFO);
        if (mPMap == null || mPMap.size() == 0) {
            mPMap = new LinkedHashMap<>();
        }

        // 添加公共参数
        mPMap.put(Constant.USERID, getUserId());
        mPMap.put(Constant.DEVICE, Constant.PLATFORM);
        mPMap.put(Constant.TOKENKEY, AppCenter.getTokenKey());

        //页面列表
        if (mPageList == null) {
            mPageList = new ArrayList<>();
        }
        mStep1Fragment = new Step1Fragment();
        mStep2Fragment = new Step2Fragment();
        mStep3Fragment = new Step3Fragment();
        mPageList.add(mStep1Fragment);
        mPageList.add(mStep2Fragment);
        mPageList.add(mStep3Fragment);
        mVpPerson.setAdapter(new SelfPageAdapter(getSupportFragmentManager(), mPageList));
        mVpPerson.setOffscreenPageLimit(2);
    }

    @Override
    protected void initData() {

    }

    public void getCity() {
        mPresenter.getCity();
    }

    @Override
    protected void initListener() {
        /**
         * viewpager的监听 点击viewpager改变radiogroup
         */
        mVpPerson.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                int check = R.id.person_self;
                switch (position) {
                    case 0:
                        check = R.id.person_self;
                        break;
                    case 1:
                        check = R.id.bg_person_job;
                        break;
                    case 2:
                        check = R.id.bg_person_shehui;
                        break;
                }
                mRgPerson.check(check);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        /**
         * radiogroup的监听 点击radiogroup改变viewpager
         */
        mRgPerson.setOnCheckedChangeListener((group, checkedId) -> {
            int check = 0;
            switch (checkedId) {
                case R.id.person_self:
                    check = 0;
                    break;
                case R.id.bg_person_job:
                    check = 1;
                    break;
                case R.id.bg_person_shehui:
                    check = 2;
                    break;
            }
            mVpPerson.setCurrentItem(check);
        });
    }

    @Override
    protected boolean needFullScreen() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void sendSuccess(HttpWrapper<String> bean) {
        switch (bean.code) {
            case Constant.SUCCESS_CODE:
                startActivity(new Intent(this, LimitActivity.class));
                finish();
                break;
            case Constant.ERROR_CODE:
                showMessage(bean.info);
                break;
            case "210":
                U.toDrainage(this, DrainageActivity.TYPE_BLACK, Constant.REFUES);
                break;
            case "220":
                U.showDialogJuJue(this, Constant.REFUES);
                break;
            case Constant.TOKEN_TIMEOUT:
                U.tokenOut(this);
                break;
            case "300":
                U.showDialogJuJue(this, Constant.REFUES);
                break;
            default:
                showMessage(bean.info);
                break;
        }
    }

    @Override
    public void readCityError(Throwable error) {

    }

    @Override
    public void readCitySuccess(City city) {
        mCityMap = new HashMap<>();

        if (Constant.SUCCESS_CODE.equals(city.getCode())) {
            ArrayList<String> province = new ArrayList<>();
            for (City.DataBean dataBean : city.getData()) {
                ArrayList<String> list = new ArrayList<>();
                for (City.DataBean.ChildBean childBean : dataBean.getChild()) {
                    list.add(childBean.getName());
                }
                mCityMap.put(dataBean.getName(), list);
                province.add(dataBean.getName());
            }
            mStep2Fragment.setPro(mCityMap, province);

            /**
             * 存入缓存
             */
            UserUtil.setCache(UserUtil.CITYINFO, city);
        }
    }

    public void stepContinue(int position) {
        if (position == 2) {
            if (mStep1Fragment.check(true) && mStep2Fragment.check(true)) {
                mPresenter.sendService(mPMap, getToken());
            }
            return;
        }

        mVpPerson.setCurrentItem(++position);
    }

    public void selectContact(int code) {
        mCode = code;
        mRxPermissions
                .request(Manifest.permission.READ_CONTACTS, Manifest.permission.GET_ACCOUNTS)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent, UserConstant.SELECT_FCONTACT);
                    } else {
                        U.getSingleDialog(this, "温馨提示", "读取通讯录权限可能被拒绝,请先开启权限", "确定"
                                , () -> {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package", this.getPackageName(), null);
                                    intent.setData(uri);
                                    startActivity(intent);
                                });
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            String username = null;
            String usernumber = null;
            ContentResolver reContentResolverol = getContentResolver();
            Uri contactData = data.getData();
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                            null,
                            null);
                    /**
                     * 没有手机号码
                     */
                    if (phone == null) {
                        showMessage("该用户可能并没有手机号码");
                        return;
                    }
                    if (phone.moveToNext()) {
                        usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        mStep3Fragment.setPhoneAndName(mCode, usernumber, username);
                    }
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mStep1Fragment.check(false);
        mStep2Fragment.check(false);
        UserUtil.setCache(UserUtil.PERSONINFO, mPMap);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
